package	com.sdry.service.impl.jyy.unpack;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.mapper.barCodeOperation.BarCodeOperationMapper;
import com.sdry.mapper.jyy.ReceiveDetailMapper;
import com.sdry.mapper.jyy.unpack.JyyUnpackingMapper;
import com.sdry.mapper.jyy.unpack.UnpackDetalCodeMapper;
import com.sdry.mapper.jyy.unpack.UnpackDetalMapper;
import com.sdry.mapper.llm.CancellingStockDetailMapper;
import com.sdry.mapper.llm.DevaningWorkMapper;
import com.sdry.mapper.lz.InventoryMapper;
import com.sdry.mapper.lz.MaterielMapper;
import com.sdry.mapper.lz.StockOutOrderMapper;
import com.sdry.mapper.lz.WarehouseMapper;
import com.sdry.mapper.tdd.OthersMapper;
import com.sdry.mapper.zc.ZcUpAndDownMapper;
import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.ReceiveDetailQuality;
import com.sdry.model.jyy.Workload;
import com.sdry.model.jyy.unpack.JyyUnpacking;
import com.sdry.model.jyy.unpack.UnpackDetal;
import com.sdry.model.jyy.unpack.UnpackDetalCode;
import com.sdry.model.llm.DevaningLog;
import com.sdry.model.llm.DevaningWork;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.ReceiveMark;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcTrayAndLocationEntity;
import com.sdry.service.jyy.unpack.UnpackDetalService;
import com.sdry.utils.BarCodeUtils;
import com.sdry.utils.DateUtil;
import com.sdry.utils.QRCodeUtil;
import com.sdry.utils.RootPath;
import com.sdry.utils.StringUtil;
import com.sdry.utils.CodeUtil;
/**
 *
 *@ClassName: UnpackDetalService
 *@Description: 
 *@Author jyy
 *@Date 2019-08-20 15:58:14
 *@version 1.0
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class UnpackDetalServiceImpl implements UnpackDetalService {
	
	@Resource UnpackDetalMapper unpackDetalMapper;
	@Resource WarehouseMapper warehouseMapper;
	@Resource UnpackDetalCodeMapper unpackDetalCodeMapper;
	@Resource MaterielMapper materielMapper;
	@Resource OthersMapper othersMapper;
	
	@Resource ReceiveDetailMapper receiveDetailMapper;
	@Resource JyyUnpackingMapper jyyUnpackingMapper;
	@Resource CancellingStockDetailMapper cancellingStockDetailMapper;
	@Resource DevaningWorkMapper devaningWorkMapper;
	@Resource BarCodeOperationMapper barCodeOperationMapper;
	@Resource InventoryMapper inventoryMapper;
	@Resource StockOutOrderMapper stockOutMapper;
	@Resource ZcUpAndDownMapper zcUpAndDownMapper;
	
	/** 	
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	public UnpackDetal queryById(Long id) {
		return unpackDetalMapper.queryById(id);
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	public List<UnpackDetal> queryAllByMution(UnpackDetal param) {
		return unpackDetalMapper.queryAllByMution(param);
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @return 实体集合
	*/
	public List<UnpackDetal> findPageByMution(UnpackDetal param) {
		return unpackDetalMapper.findPageByMution(param);
	}
	/** 
	 * 条件查询记录数
	 * @param param 实体条件
	 * @return 实体集合
	*/
	public Integer selectCountByMution(UnpackDetal param) {
		return unpackDetalMapper.selectCountByMution(param);
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @return 主键id
	 */
	public Long insert(UnpackDetal param) {
		return unpackDetalMapper.insert(param);
	}
		
	ReceiveMark receiveMarkSrc = new ReceiveMark();
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @return 主键id
	*/
	public Long insertNew(UnpackDetal param , HttpSession httpSession) {
		
		//获取session中的仓库id
		Long warehouseId = (Long) httpSession.getAttribute("warehouse_id");
		String warehouse = "";
		List<Warehouse> queryAllWarehouse = warehouseMapper.queryAllWarehouse(warehouseId);
		if(queryAllWarehouse.size() == 1){
			warehouse = queryAllWarehouse.get(0).getWarehouse_num();
		}
		
		param.setState(0);
		Long identity = unpackDetalMapper.insert(param);
		
		//计算条码数量
		//1.需拆箱总数
		Integer znum = param.getZnum();
		//2.拆箱规格
		Integer specs = param.getSpecs();
		//拆箱后 条码数
		int boxNum = znum % specs == 0 ? (znum/specs) : (znum/specs)+1;
		
		int yu = specs;
		if(znum % specs != 0) {
			//计算最后一个条码中的数量
			yu = znum % specs;
		}
	
		Label(warehouse,param.getMid(), param.getPici(), boxNum, identity, yu, specs);
		
		return identity;
	}
	/*=======================条码工具类===========================*/
	public void Label(String warehouse,Long mid, String pici, int num, Long identity, int yu, Integer specs) {
		Materiel materiel = materielMapper.queryMaterielById(mid);
		//根据物料id查询客户的remark
		Customer customer = materielMapper.queryCustomerByCustomerId(materiel.getCustomer_id());
		String s = materiel.getSequence_number();
		String snum = "";
		String slast = "A";
		if(null != s && !"".equals(s)){
			snum = s.substring(0,s.length() - 1);
			slast = s.substring(s.length() - 1,s.length());       
		}
		int sequence_number = StringUtil.strNum(snum);
		List<List<String>> list = new ArrayList<>();
		
		//生成条码存入拆箱明细条码表中
		UnpackDetalCode unpackDetalCode = new UnpackDetalCode();
		//生成条码及二维码
		for (int i = 1; i <= num; i++) {
			
			List<String> codelist = new ArrayList<>();
			if((sequence_number + i) > 999999){
				sequence_number = 0;
                num = num - i;
				i = 0;
				slast = CodeUtil.getNextUpEn(slast);
			}
			try {
				codelist = getcode(warehouse,customer.getCustomer_num(), materiel.getMateriel_num(), pici,(sequence_number+i)+slast);
			}catch (Exception e) {
				e.printStackTrace();
			}
			list.add(codelist);
			codelist = null;
			
			//收货单详细的自增主键
			unpackDetalCode.setDid(identity);
			if (i == num - 1) {
				unpackDetalCode.setNum(yu);
			} else {
				unpackDetalCode.setNum(specs);
			}
			//=========按规则生成的条码=========
			try {
			} catch (Exception e) {
				e.printStackTrace();
			}
			//============================
			//生成的条码
			unpackDetalCode.setCode(receiveMarkSrc.getCode());
			//二维码路径
			unpackDetalCode.setTwoCodePath(receiveMarkSrc.getTwoCodePath());
			//一维码路径
			unpackDetalCode.setBarCodePath(receiveMarkSrc.getBarCodePath());
			
			//向条码表中添加条码
			unpackDetalCodeMapper.insert(unpackDetalCode);
			
		}
		updateNumber(materiel.getId(),sequence_number+num+slast);
	}
	
	/**
	 * 获取条码
	 * @param client
	 * @param Materiel_num
	 * @param Batch
	 * @param Sequence_number
	 * @return
	 * @throws FileNotFoundException
	 * @throws Exception
	 */
	public List<String> getcode(String warehouse,String client, String Materiel_num, String Batch,String Sequence_number) throws FileNotFoundException, Exception{
		List<String> list = new ArrayList<>();
		String code =  CodeUtil.getCodes(warehouse,client, Materiel_num, Batch, Sequence_number);
		System.out.println("生成的条码：" + code);
		list.add(code);
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 可以方便地修改日期格式
		String datetime = dateFormat.format(now);
		String twoCodeDir = RootPath.getRootPath("RECEIVE_TWO_RCODE_PATH");
		String barCodeDir = RootPath.getRootPath("RECEIVE_BAR_RCODE_PATH");
		String rcodeTwoCodName = "rcode//receive_two_rcode//" + "receive_two_"+Materiel_num + datetime + Sequence_number + ".png";
		String rcodeBarCodName = "rcode//receive_bar_rcode//" + "receive_bar_"+Materiel_num + datetime + Sequence_number + ".png";
		String path = twoCodeDir + rcodeTwoCodName;
		String path1 = barCodeDir + rcodeBarCodName;
        File file = new File(path);
        //生成二维码
        QRCodeUtil.encode(code, null, new FileOutputStream(file), true);
        //生成条形码
        BarCodeUtils.BarCodeImage(code, path1);
        list.add(path);
        list.add(path1);
        receiveMarkSrc.setCode(code);
        receiveMarkSrc.setTwoCodePath(rcodeTwoCodName);
        receiveMarkSrc.setBarCodePath(rcodeBarCodName);
		return list;
	}
	
	/**
	 * 根据物料主键更新物料顺序号
	 * @param id 物料主键
	 * @param num 顺序号
	 * @return
	 */	
	public int updateNumber(Long id,String num){	
		int count = othersMapper.updateMateriel(id,num);
		return count;
	}
	
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @return 影响行数
	*/
	@Transactional
	public Integer update(UnpackDetal param) {
		return unpackDetalMapper.update(param);
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	public Integer delete(String ids) {
		return unpackDetalMapper.delete(ids);
	}
	/**
	 * 根据员工姓名 查询员工id
	 * @param workman 员工姓名 
	 * @return 员工id
	 */
	@Override
	public Long selectUidByUname(String workman) {
		return unpackDetalMapper.selectUidByUname(workman);
	}
	
	/**
	 * app拆箱计划拆箱提交
	 * @param json1 所有 拆箱前 的条码信息
	 * @param json2 所有 拆箱后 的条码信息
	 * @param userId 工作量报工情况
	 * @param unpackDetail 拆箱详情
	 * @param warehouse_id 仓库id
	 */
	@Override
	public int devanning(String json1, String json2, String userId, String unpackDetail, String warehouse_id) {
		int snum = 0;
		int znum  = 0;
		int affact = 0;
		String newPici = "";
		Gson gson = new Gson();
		//拆箱详情
		UnpackDetal unpackDetal2=  gson.fromJson(unpackDetail, UnpackDetal.class);
		Long did = unpackDetal2.getId();
		if(!"".equals(unpackDetal2.getZnum()) && null != unpackDetal2.getZnum()) {
			znum = unpackDetal2.getZnum();
		}
		
		//拆箱前
		List<CodeMark> codeMarkList1 = gson.fromJson(json1, new TypeToken<List<CodeMark>>() {}.getType());
		//拆箱后
		List<CodeMark> codeMarkList2 = gson.fromJson(json2, new TypeToken<List<CodeMark>>() {}.getType());
		//工作量
		List<Workload> workList = gson.fromJson(userId, new TypeToken<List<Workload>>() {}.getType());
		//累加获取拆箱后总数
		for (CodeMark codeMark : codeMarkList2) {
			snum = snum + codeMark.getNum();
		}
		
	//********************************************tdd************************************
	//1.1、找到旧条码中第一个条码的位置
	CodeMark codeMark = cancellingStockDetailMapper.queryCodeByCode(codeMarkList1.get(0).getCode());
	String code = ","+codeMarkList1.get(0).getCode()+",";
	ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = receiveDetailMapper.queryMaterielTrayByCode(code);
	if(zcMaterielAndTrayEntity != null){
		//现在条码
		List<CodeMark> codeMarkListX = codeMarkList2;
		//原有条码
		List<CodeMark> codeMarkListY = codeMarkList1;
		//现在条码比较原有条码新增
		List<CodeMark> codeMarkListXS = new ArrayList<>();
		
		for (int j = 0; j < codeMarkListY.size(); j++) {
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = receiveDetailMapper.queryMaterielTrayByCode(codeMarkListY.get(j).getCode());
			CodeMark CodeMark = receiveDetailMapper.queryCodeMarkByCode(codeMarkListY.get(j));
			//在新条码中是否查询到此次循环旧条码 0 否 1是
			int flg = 0;
			for (int k = 0; k < codeMarkListX.size(); k++) {
				//此次循环新条码  == 此次循环旧条码
				if(codeMarkListX.get(k).getCode().equals(codeMarkListY.get(j).getCode())){
					//修改物料托盘信息
					if(zcMaterielAndTrayEntity1 != null){
						int num = zcMaterielAndTrayEntity1.getmNum()-codeMarkListY.get(j).getNum()+codeMarkListX.get(k).getNum();
						inventoryMapper.updateById(zcMaterielAndTrayEntity1.getId()+"", "mNum", num+"", "zc_materiel_tray");
					}
					//修改记录
					//根据精准码查询是否存在
					if (CodeMark != null) {
						receiveDetailMapper.updateCodeMark(codeMarkListX.get(k));
					} else {
						//绑定新条码
						receiveDetailMapper.addCodeMark(codeMarkListX.get(k));
					}
					flg = 1;
					break;
				}
			}
			//没有找到
			if(flg == 0){
				//删除托盘物料
				if(zcMaterielAndTrayEntity1 != null){
					String mCode = zcMaterielAndTrayEntity1.getMateriel_code();
					//用空字符串替换旧条码
					String newCode2 = mCode.replace(codeMarkListY.get(j).getCode()+",", "");
					if(newCode2.length() == 0){
						//如果托盘空了，则删除这条数据(现在不能删，只有添加新条码后，再盘点托盘为空，进行删除，新条码有可能放回来)
						receiveDetailMapper.deleteMaterielTrayById(zcMaterielAndTrayEntity1.getId());
					}else{
						//把替换后的条码集合放回原来托盘
						receiveDetailMapper.updateMaterielTrayByCode(zcMaterielAndTrayEntity1.getId() + "", newCode2);
						//根据精准码查询是否存在
						if (codeMark != null) {
							inventoryMapper.updateById(zcMaterielAndTrayEntity1.getId()+"", "mNum", (zcMaterielAndTrayEntity1.getmNum()-codeMark.getNum())+"", "zc_materiel_tray");
						} 
					}
				}
				//删除记录
				stockOutMapper.deleteCodemarkOutByCode(codeMarkListY.get(j).getCode());
			}
		}
		
		for (int j = 0; j < codeMarkListX.size(); j++) {
			//在新条码中是否查询到此次循环旧条码 0 否 1是
			int flg = 0;
			for (int k = 0; k < codeMarkListY.size(); k++) {
				if(codeMarkListX.get(j).getCode().equals(codeMarkListY.get(k).getCode())){
					flg = 1;
					break;
				}
			}
			if(flg == 0){
				codeMarkListXS.add(codeMarkListX.get(j));
			}
		}
		if(codeMarkListXS.size() > 0){
			String codes = "";
			int sum = 0;
			for (CodeMark codeMark1 : codeMarkListXS) {
				codes += codeMark1.getCode() + ",";
				sum += codeMark1.getNum();
				//绑定新条码
				receiveDetailMapper.addCodeMark(codeMark1);
			}
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = new ZcMaterielAndTrayEntity();
			zcMaterielAndTrayEntity1.setMid(zcMaterielAndTrayEntity.getMid());
			newPici = zcMaterielAndTrayEntity.getmBatch();
			zcMaterielAndTrayEntity1.setmBatch(zcMaterielAndTrayEntity.getmBatch());
			zcMaterielAndTrayEntity1.setMateriel_code(codes);
			String tray_code = System.currentTimeMillis()+"";
			zcMaterielAndTrayEntity1.setTray_code(tray_code);
			zcMaterielAndTrayEntity1.setmNum(sum);
			
			//操作人姓名
			String username = workList.get(0).getWorkman();
			//根据员工姓名查询员工id
			Long uid = unpackDetalMapper.selectUidByUname(username);
			zcMaterielAndTrayEntity.setBinding_person(uid);
			
			zcMaterielAndTrayEntity1.setBinding_person(uid);
			zcMaterielAndTrayEntity1.setBinding_date(DateUtil.dateFormat3());
			inventoryMapper.MaterielTrayInsert(zcMaterielAndTrayEntity1);
			ZcTrayAndLocationEntity a = new ZcTrayAndLocationEntity();
			a.setLocation_code("HC");
			
			//------------jyy2019-09-11-07start----------------
			a.setWarehouse_id(Long.valueOf(warehouse_id));
			//------------jyy2019-09-11-07end------------------
			
			//根据库位查询
			ZcTrayAndLocationEntity zcTrayAndLocationEntityOld = zcUpAndDownMapper.selectTrayCodeByLocationCode(a);
			//3、如果不为空，修改数据
			if(zcTrayAndLocationEntityOld != null){
				String trayCodes = zcTrayAndLocationEntityOld.getTray_code() + zcMaterielAndTrayEntity1.getTray_code() + ",";
				inventoryMapper.updateById(zcTrayAndLocationEntityOld.getId()+"", "tray_code", trayCodes, "zc_tray_location");
			}else{
				//4、新增库位至待检区
				ZcTrayAndLocationEntity zcTrayAndLocationEntity = new ZcTrayAndLocationEntity();
				//托盘码
				zcTrayAndLocationEntity.setTray_code(tray_code);
				//库区编码
				zcTrayAndLocationEntity.setLocation_code("HC");
				//库区编码
				zcTrayAndLocationEntity.setWarehouse_id(Long.valueOf(warehouse_id));
				//绑定人
				zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity1.getBinding_person());
	    		//绑定时间
				zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity1.getBinding_date());
				inventoryMapper.trayLocationInsert(zcTrayAndLocationEntity);
			}
		}
	}
	//**************************************************************tdd******************************************************
		
	//**************************************************工作量****************************************************************			
		Date date = new Date();
		DevaningLog dl = new DevaningLog();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = sdf.format(date);
		dl.setWork_time(time);
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String time2 = sdf2.format(date);
		dl.setNumber(time2);
		
		String workman = workList.get(0).getWorkman();
		
		//根据员工姓名查询员工id
		Long uid = unpackDetalMapper.selectUidByUname(workman);
		
		//保存工作量
		DevaningWork dw = new DevaningWork();
		dw.setUserName(workman);
		dw.setLogNumber(time2);
		dw.setWarehouse_id(Long.valueOf(warehouse_id));
		for(Workload work : workList){
			dw.setBoxQuantity(work.getGood_num());
			dw.setPcsQuantity(work.getNgood_num());
			devaningWorkMapper.insert(dw);
		}
		//**************************************************工作量****************************************************************	
		///////////////////////////////////////////////////////jyy-拆箱单据处理////////////////////////////////////////////////////////////////////		
		//更新拆箱详情中拆箱数量
		UnpackDetal unpackDetal = new UnpackDetal();
		//详情id
		unpackDetal.setId(Long.valueOf(did));
		snum = unpackDetal2.getUnum() + snum;
		
		//拆箱数量
		unpackDetal.setUnum(snum);
		
		if( znum > snum) {
			unpackDetal.setState(1);
		}else if(znum <= snum){
			unpackDetal.setState(2);
		}
		
		unpackDetalMapper.update(unpackDetal);
		
		//根据单号查询拆箱计划单信息
		JyyUnpacking param = new JyyUnpacking();
		param.setOrdernum(unpackDetal2.getOrdernum());
		List<JyyUnpacking> JyyUnpackings = jyyUnpackingMapper.queryAllByMution(param);
		if(JyyUnpackings.size() > 0) {
			JyyUnpacking jyyUnpacking = JyyUnpackings.get(0);
			Long id = jyyUnpacking.getId();
			param.setId(id);
			
			//如果，单子中没有，则添加拆箱人，拆箱时间
			if("".equals(jyyUnpacking.getUnpackName()) || null == jyyUnpacking.getUnpackName() ) {
				
				param.setUnpackName(uid);
				param.setUnpackDate(DateUtil.dateFormat3());
			}
			//根据单号查询此单子的所有详情
			UnpackDetal unpackDetalQery = new UnpackDetal();
			unpackDetalQery.setOrdernum(jyyUnpacking.getOrdernum());
			//此查询结果为：所有状态不为2的详情集合
			List<UnpackDetal> queryAllByMutions = unpackDetalMapper.queryAllByMution(unpackDetalQery );
			//判断是否有不为2的详情
			if(queryAllByMutions.size() > 0) {
				//有：修改状态为未完成
				param.setState(1);
			}else{
				//没有，则修改单子的状态为2
				param.setState(2);
			}
			//修改单子的状态及拆箱信息
			jyyUnpackingMapper.update(param);
		}
		/////////////////////////////////////////////jyy-拆箱单据处理////////////////////////////////////////////////////////////////////				
		Long receive_detail_id = codeMarkList1.get(0).getReceive_detail_id();
		//1.遍历json1进行删除
		for (int i = 0; i < codeMarkList1.size(); i++) {
			dl.setDetail_id(receive_detail_id);
			dl.setCode(codeMarkList1.get(i).getCode());
			dl.setQuantity(codeMarkList1.get(i).getNum());
			dl.setIs_ng(codeMarkList1.get(i).getIs_ng());
			dl.setStatus(0);
			dl.setWarehouse_id(Long.valueOf(warehouse_id));
			//添加拆箱前记录
			cancellingStockDetailMapper.insertDevaning(dl);
		}
		//2.遍历json2进行增加
		for (int i = 0; i < codeMarkList2.size(); i++) {
			dl.setDetail_id(receive_detail_id);
			dl.setCode(codeMarkList2.get(i).getCode());
			dl.setQuantity(codeMarkList2.get(i).getNum());
			dl.setIs_ng(codeMarkList2.get(i).getIs_ng());
			dl.setStatus(1);
			dl.setWarehouse_id(Long.valueOf(warehouse_id));
			//添加拆箱后记录
			affact = cancellingStockDetailMapper.insertDevaning(dl);
			//添加每种物料对应的多个条码
			codeMarkList2.get(i).setReceive_detail_id(receive_detail_id);
			
			//--------------给历史记录表插入数据--------------
			BarCodeOperation bar = new BarCodeOperation();
			
			bar.setOperator(uid);
			bar.setMaterielId(unpackDetal2.getMid());
			bar.setBatch(newPici);
			bar.setOperatingTime(time);
			bar.setType("计划拆箱");
			bar.setWarehouse_id(Long.valueOf(warehouse_id));
			if(codeMarkList1.size() > 0){
				bar.setResult("成功");
			}else{
				bar.setResult("失败");
			}
			bar.setBarCode(codeMarkList2.get(i).getCode());
			bar.setCodeNum(codeMarkList2.get(i).getNum());
			//新增条码操作记录
			barCodeOperationMapper.insert(bar);
			//--------------给历史记录表插入数据--------------
		}
		
		return affact;
	}
	
	/**
	 * 拆箱作业
	 * @param codeMarkList1 所有 拆箱前 的条码信息
	 * @param codeMarkList2  所有 拆箱后 的条码信息
	 * @param workList 工作量报工情况
	 * @return 
	 */
	@Override
	public int devanningWork(List<CodeMark> codeMarkList1, List<CodeMark> codeMarkList2,
				List<Workload> workList, String warehouse_id, CodeMark codeMark, ZcMaterielAndTrayEntity zcMaterielAndTrayEntity) {
		int affact = 0;
		//********************************************tdd************************************
		//现在条码
		List<CodeMark> codeMarkListX = codeMarkList2;
		//原有条码
		List<CodeMark> codeMarkListY = codeMarkList1;
		//现在条码比较原有条码新增
		List<CodeMark> codeMarkListXS = new ArrayList<>();
		
		for (int j = 0; j < codeMarkListY.size(); j++) {
			//在新条码中是否查询到此次循环旧条码 0 否 1是
			int flg = 0;
			for (int k = 0; k < codeMarkListX.size(); k++) {
				//此次循环新条码  == 此次循环旧条码
				if(codeMarkListX.get(k).getCode().equals(codeMarkListY.get(j).getCode())){
					//修改物料托盘信息
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = receiveDetailMapper.queryMaterielTrayByCode(codeMarkListY.get(j).getCode());
					if(zcMaterielAndTrayEntity1 != null){
						int num = zcMaterielAndTrayEntity1.getmNum()-codeMarkListY.get(j).getNum()+codeMarkListX.get(k).getNum();
						inventoryMapper.updateById(zcMaterielAndTrayEntity1.getId()+"", "mNum", num+"", "zc_materiel_tray");
					}
					//修改记录
					//根据精准码查询是否存在
					CodeMark CodeMark = receiveDetailMapper.queryCodeMarkByCode(codeMarkListY.get(j));
					if (CodeMark != null) {
						receiveDetailMapper.updateCodeMark(codeMarkListX.get(k));
					} else {
						//绑定新条码
						receiveDetailMapper.addCodeMark(codeMarkListX.get(k));
					}
					flg = 1;
					break;
				}
			}
			//没有找到
			if(flg == 0){
				//删除托盘物料
				ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = receiveDetailMapper.queryMaterielTrayByCode(codeMarkListY.get(j).getCode());
				if(zcMaterielAndTrayEntity1 != null){
					String mCode = zcMaterielAndTrayEntity1.getMateriel_code();
					//用空字符串替换旧条码
					String newCode2 = mCode.replace(codeMarkListY.get(j).getCode()+",", "");
					if(newCode2.length() == 0){
						//如果托盘空了，则删除这条数据(现在不能删，只有添加新条码后，再盘点托盘为空，进行删除，新条码有可能放回来)
						receiveDetailMapper.deleteMaterielTrayById(zcMaterielAndTrayEntity1.getId());
					}else{
						//把替换后的条码集合放回原来托盘
						receiveDetailMapper.updateMaterielTrayByCode(zcMaterielAndTrayEntity1.getId() + "", newCode2);
						//根据精准码查询是否存在
						CodeMark codeMark1 = receiveDetailMapper.queryCodeMarkByCode(codeMarkListY.get(j));
						if (codeMark1 != null) {
							inventoryMapper.updateById(zcMaterielAndTrayEntity1.getId()+"", "mNum", (zcMaterielAndTrayEntity1.getmNum()-codeMark.getNum())+"", "zc_materiel_tray");
						} 
					}
				}
				//删除记录
				stockOutMapper.deleteCodemarkOutByCode(codeMarkListY.get(j).getCode());
			}
		}
		
		for (int j = 0; j < codeMarkListX.size(); j++) {
			//在新条码中是否查询到此次循环旧条码 0 否 1是
			int flg = 0;
			for (int k = 0; k < codeMarkListY.size(); k++) {
				if(codeMarkListX.get(j).getCode().equals(codeMarkListY.get(k).getCode())){
					flg = 1;
					break;
				}
			}
			if(flg == 0){
				codeMarkListXS.add(codeMarkListX.get(j));
			}
		}
		if(codeMarkListXS.size() > 0){
			String codes = "";
			int sum = 0;
			for (CodeMark codeMark1 : codeMarkListXS) {
				codes += codeMark1.getCode() + ",";
				sum += codeMark1.getNum();
				//绑定新条码
				receiveDetailMapper.addCodeMark(codeMark1);
			}
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = new ZcMaterielAndTrayEntity();
			zcMaterielAndTrayEntity1.setMid(zcMaterielAndTrayEntity.getMid());
			zcMaterielAndTrayEntity1.setmBatch(zcMaterielAndTrayEntity.getmBatch());
			zcMaterielAndTrayEntity1.setMateriel_code(codes);
			String tray_code = System.currentTimeMillis()+"";
			zcMaterielAndTrayEntity1.setTray_code(tray_code);
			zcMaterielAndTrayEntity1.setmNum(sum);
			
			//操作人姓名
			String username = workList.get(0).getWorkman();
			//根据员工姓名查询员工id
			Long uid = unpackDetalMapper.selectUidByUname(username);
			zcMaterielAndTrayEntity.setBinding_person(uid);
			
			zcMaterielAndTrayEntity1.setBinding_person(uid);
			zcMaterielAndTrayEntity1.setBinding_date(DateUtil.dateFormat3());
			//LZ新增warehouse_id字段
			zcMaterielAndTrayEntity1.setWarehouse_id(Long.parseLong(warehouse_id));
			inventoryMapper.MaterielTrayInsert(zcMaterielAndTrayEntity1);
			ZcTrayAndLocationEntity a = new ZcTrayAndLocationEntity();
			a.setLocation_code("HC");
			//lz新增warehouse_id
			a.setWarehouse_id(Long.parseLong(warehouse_id));
			//根据库位查询
			ZcTrayAndLocationEntity zcTrayAndLocationEntityOld = zcUpAndDownMapper.selectTrayCodeByLocationCode(a);
			//3、如果不为空，修改数据
			if(zcTrayAndLocationEntityOld != null){
				String trayCodes = zcTrayAndLocationEntityOld.getTray_code() + zcMaterielAndTrayEntity1.getTray_code() + ",";
				inventoryMapper.updateById(zcTrayAndLocationEntityOld.getId()+"", "tray_code", trayCodes, "zc_tray_location");
			}else{
				//4、新增库位至待检区
				ZcTrayAndLocationEntity zcTrayAndLocationEntity = new ZcTrayAndLocationEntity();
				//托盘码
				zcTrayAndLocationEntity.setTray_code(tray_code);
				//库区编码
				zcTrayAndLocationEntity.setLocation_code("HC");
				//绑定人
				zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity1.getBinding_person());
	    		//绑定时间
				zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity1.getBinding_date());
				//lz新增warehouse_id
				zcTrayAndLocationEntity.setWarehouse_id(Long.parseLong(warehouse_id));
				inventoryMapper.trayLocationInsert(zcTrayAndLocationEntity);
			}
		}
		
		Date date = new Date();
		DevaningLog dl = new DevaningLog();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = sdf.format(date);
		dl.setWork_time(time);
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String time2 = sdf2.format(date);
		dl.setNumber(time2);
		
		//保存工作量
		DevaningWork dw = new DevaningWork();
		dw.setUserName(workList.get(0).getWorkman());
		dw.setLogNumber(time2);
		//LZ新增warehouse_id
		dw.setWarehouse_id(Long.parseLong(warehouse_id));
		for(Workload work : workList){
			dw.setBoxQuantity(work.getGood_num());
			dw.setPcsQuantity(work.getNgood_num());
			devaningWorkMapper.insert(dw);
		}
		Long Receive_detail_id=codeMarkList1.get(0).getReceive_detail_id();
		
		ReceiveDetailQuality byCode = inventoryMapper.queryReceiveByCode(codeMarkList2.get(0).getCode());
		//1.遍历json1进行删除
		for (int i = 0; i < codeMarkList1.size(); i++) {
			dl.setDetail_id(Receive_detail_id);
			dl.setCode(codeMarkList1.get(i).getCode());
			dl.setQuantity(codeMarkList1.get(i).getNum());
			dl.setIs_ng(codeMarkList1.get(i).getIs_ng());
			dl.setStatus(0);
			dl.setWarehouse_id(Long.parseLong(warehouse_id));
			
			//--------------给历史记录表插入数据--------------
			BarCodeOperation bar = new BarCodeOperation();
			Long id = barCodeOperationMapper.queryIdByName(workList.get(0).getWorkman());
			bar.setOperator(id);
			bar.setMaterielId(byCode.getMid());
			bar.setBatch(byCode.getPici());
			bar.setOperatingTime(time);
			bar.setType("拆箱前");
			bar.setResult("成功");
			bar.setBarCode(codeMarkList1.get(i).getCode());
			bar.setCodeNum(codeMarkList1.get(i).getNum());
			//LZ新增warehouse_id
			bar.setWarehouse_id(Long.parseLong(warehouse_id));
			barCodeOperationMapper.insert(bar);
			//--------------给历史记录表插入数据--------------
			
			cancellingStockDetailMapper.insertDevaning(dl);
		}
		//2.遍历json2进行增加
		for (int i = 0; i < codeMarkList2.size(); i++) {
			dl.setDetail_id(Receive_detail_id);
			dl.setCode(codeMarkList2.get(i).getCode());
			dl.setQuantity(codeMarkList2.get(i).getNum());
			dl.setIs_ng(codeMarkList2.get(i).getIs_ng());
			dl.setStatus(1);
			dl.setWarehouse_id(Long.parseLong(warehouse_id));
			affact = cancellingStockDetailMapper.insertDevaning(dl);
			//添加每种物料对应的多个条码
			//ReceiveDetailService.addCodeMark(codeMarkList2.get(i));
			
			//--------------给历史记录表插入数据--------------
			BarCodeOperation bar = new BarCodeOperation();
			Long id = barCodeOperationMapper.queryIdByName(workList.get(0).getWorkman());
			bar.setOperator(id);
			bar.setMaterielId(byCode.getMid());
			bar.setBatch(byCode.getPici());
			bar.setOperatingTime(time);
			bar.setType("拆箱后");
			bar.setResult("成功");
			bar.setBarCode(codeMarkList2.get(i).getCode());
			bar.setCodeNum(codeMarkList2.get(i).getNum());
			//LZ新增warehouse_id
			bar.setWarehouse_id(Long.parseLong(warehouse_id));
			barCodeOperationMapper.insert(bar);
			//--------------给历史记录表插入数据--------------
		}
		
		return affact;
	}
}
